<template>
  <div class="calculator">
    <!-- 显示屏 -->
    <div class="calculator-display">
      <div class="display-value">{{ displayValue }}</div>
    </div>

    <!-- 按钮区域 -->
    <div class="calculator-buttons">
      <!-- 第一行 -->
      <button class="btn btn-gray" @click="handleClear">{{ clearLabel }}</button>
      <button class="btn btn-gray" @click="handleToggleSign">+/-</button>
      <button class="btn btn-gray" @click="handlePercent">%</button>
      <button class="btn btn-operator" @click="handleOperator('÷')">÷</button>

      <!-- 第二行 -->
      <button class="btn btn-number" @click="handleNumber('7')">7</button>
      <button class="btn btn-number" @click="handleNumber('8')">8</button>
      <button class="btn btn-number" @click="handleNumber('9')">9</button>
      <button class="btn btn-operator" @click="handleOperator('×')">×</button>

      <!-- 第三行 -->
      <button class="btn btn-number" @click="handleNumber('4')">4</button>
      <button class="btn btn-number" @click="handleNumber('5')">5</button>
      <button class="btn btn-number" @click="handleNumber('6')">6</button>
      <button class="btn btn-operator" @click="handleOperator('−')">−</button>

      <!-- 第四行 -->
      <button class="btn btn-number" @click="handleNumber('1')">1</button>
      <button class="btn btn-number" @click="handleNumber('2')">2</button>
      <button class="btn btn-number" @click="handleNumber('3')">3</button>
      <button class="btn btn-operator" @click="handleOperator('+')">+</button>

      <!-- 第五行 -->
      <button class="btn btn-number btn-zero" @click="handleNumber('0')">0</button>
      <button class="btn btn-number" @click="handleDecimal">.</button>
      <button class="btn btn-operator" @click="handleEquals">=</button>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed } from 'vue'

const displayValue = ref('0')
const previousValue = ref<number | null>(null)
const currentOperator = ref<string | null>(null)
const waitingForOperand = ref(false)

const clearLabel = computed(() => {
  return displayValue.value !== '0' ? 'C' : 'AC'
})

function handleNumber(num: string) {
  if (waitingForOperand.value) {
    displayValue.value = num
    waitingForOperand.value = false
  } else {
    if (displayValue.value === '0') {
      displayValue.value = num
    } else {
      // 限制显示长度
      if (displayValue.value.length < 9) {
        displayValue.value += num
      }
    }
  }
}

function handleDecimal() {
  if (waitingForOperand.value) {
    displayValue.value = '0.'
    waitingForOperand.value = false
  } else if (displayValue.value.indexOf('.') === -1) {
    displayValue.value += '.'
  }
}

function handleClear() {
  displayValue.value = '0'
  previousValue.value = null
  currentOperator.value = null
  waitingForOperand.value = false
}

function handleToggleSign() {
  const value = parseFloat(displayValue.value)
  if (value !== 0) {
    displayValue.value = String(-value)
  }
}

function handlePercent() {
  const value = parseFloat(displayValue.value)
  displayValue.value = String(value / 100)
}

function handleOperator(operator: string) {
  const inputValue = parseFloat(displayValue.value)

  if (previousValue.value === null) {
    previousValue.value = inputValue
  } else if (currentOperator.value) {
    const result = performCalculation()
    displayValue.value = String(result)
    previousValue.value = result
  }

  waitingForOperand.value = true
  currentOperator.value = operator
}

function handleEquals() {
  const inputValue = parseFloat(displayValue.value)

  if (currentOperator.value && previousValue.value !== null) {
    const result = performCalculation()
    displayValue.value = formatResult(result)
    previousValue.value = null
    currentOperator.value = null
    waitingForOperand.value = true
  }
}

function performCalculation(): number {
  const prev = previousValue.value!
  const current = parseFloat(displayValue.value)

  switch (currentOperator.value) {
    case '+':
      return prev + current
    case '−':
      return prev - current
    case '×':
      return prev * current
    case '÷':
      return current !== 0 ? prev / current : 0
    default:
      return current
  }
}

function formatResult(value: number): string {
  // 处理非常大或非常小的数字
  if (Math.abs(value) > 999999999) {
    return value.toExponential(3)
  }
  
  // 移除尾随的零
  let result = value.toString()
  
  // 限制小数位数
  if (result.includes('.')) {
    const parts = result.split('.')
    if (parts[1].length > 6) {
      result = value.toFixed(6)
    }
    // 移除尾随零
    result = result.replace(/\.?0+$/, '')
  }
  
  // 限制总长度
  if (result.length > 9) {
    result = value.toExponential(3)
  }
  
  return result
}

// 键盘支持
function handleKeydown(e: KeyboardEvent) {
  const key = e.key
  
  if (key >= '0' && key <= '9') {
    handleNumber(key)
  } else if (key === '.') {
    handleDecimal()
  } else if (key === '+') {
    handleOperator('+')
  } else if (key === '-') {
    handleOperator('−')
  } else if (key === '*') {
    handleOperator('×')
  } else if (key === '/') {
    e.preventDefault()
    handleOperator('÷')
  } else if (key === 'Enter' || key === '=') {
    handleEquals()
  } else if (key === 'Escape') {
    handleClear()
  } else if (key === '%') {
    handlePercent()
  }
}

// 添加键盘事件监听
import { onMounted, onUnmounted } from 'vue'

onMounted(() => {
  window.addEventListener('keydown', handleKeydown)
})

onUnmounted(() => {
  window.removeEventListener('keydown', handleKeydown)
})
</script>

<style scoped>
.calculator {
  height: 100%;
  width: 100%;
  background: #1c1c1e;
  display: flex;
  flex-direction: column;
  padding: 48px 8px 8px;
  user-select: none;
  overflow: hidden;
  box-sizing: border-box;
}

/* 显示屏 */
.calculator-display {
  flex: 1;
  display: flex;
  align-items: flex-end;
  justify-content: flex-end;
  padding: 12px 16px;
  margin-bottom: 6px;
  min-height: 60px;
  max-height: 25%;
  overflow: hidden;
}

.display-value {
  font-size: clamp(32px, 12vw, 76px);
  font-weight: 200;
  color: white;
  letter-spacing: -2px;
  line-height: 1;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  max-width: 100%;
  text-align: right;
  font-family: -apple-system, BlinkMacSystemFont, "SF Pro Display", "Segoe UI", sans-serif;
}

/* 按钮区域 */
.calculator-buttons {
  display: grid;
  grid-template-columns: repeat(4, 1fr);
  gap: clamp(4px, 1vw, 8px);
  flex-shrink: 0;
  width: 100%;
}

/* 按钮基础样式 */
.btn {
  aspect-ratio: 1;
  border: none;
  border-radius: 50%;
  font-size: clamp(20px, 5vw, 32px);
  font-weight: 400;
  cursor: pointer;
  transition: all 0.15s ease;
  outline: none;
  color: white;
  font-family: -apple-system, BlinkMacSystemFont, "SF Pro Display", "Segoe UI", sans-serif;
  position: relative;
  overflow: hidden;
  min-width: 0;
  min-height: 0;
}

.btn::before {
  content: '';
  position: absolute;
  inset: 0;
  background: rgba(255, 255, 255, 0.2);
  border-radius: 50%;
  opacity: 0;
  transition: opacity 0.15s ease;
}

.btn:hover::before {
  opacity: 1;
}

.btn:active {
  transform: scale(0.96);
}

.btn:active::before {
  opacity: 0.4;
}

/* 数字按钮 */
.btn-number {
  background: #505050;
}

.btn-number:hover {
  background: #5a5a5a;
}

.btn-number:active {
  background: #6a6a6a;
}

/* 运算符按钮 */
.btn-operator {
  background: #ff9f0a;
  font-weight: 400;
}

.btn-operator:hover {
  background: #ffb340;
}

.btn-operator:active {
  background: #ffc670;
}

/* 灰色功能按钮 */
.btn-gray {
  background: #a6a6a6;
  color: #1c1c1e;
  font-weight: 400;
}

.btn-gray:hover {
  background: #b8b8b8;
}

.btn-gray:active {
  background: #cacaca;
}

/* 0 按钮占两列 */
.btn-zero {
  grid-column: span 2;
  border-radius: 100px;
  aspect-ratio: 2.05 / 1;
  padding-left: clamp(12px, 3vw, 24px);
  text-align: left;
  display: flex;
  align-items: center;
  justify-content: flex-start;
}

.btn-zero::before {
  border-radius: 100px;
}

/* 响应式调整 - 针对小窗口 */
@media (max-height: 450px) {
  .calculator {
    padding: 40px 6px 6px;
  }

  .calculator-display {
    min-height: 40px;
    padding: 8px 12px;
    margin-bottom: 4px;
  }

  .calculator-buttons {
    gap: 4px;
  }
}

@media (max-width: 280px) {
  .calculator {
    padding: 36px 4px 4px;
  }

  .calculator-display {
    padding: 6px 10px;
  }

  .calculator-buttons {
    gap: 3px;
  }
}

/* 针对非常小的高度 */
@media (max-height: 380px) {
  .calculator {
    padding: 32px 4px 4px;
  }

  .calculator-display {
    min-height: 30px;
    padding: 4px 8px;
    margin-bottom: 3px;
  }
}

/* 针对大窗口优化 - 限制最大宽度保持计算器的紧凑外观 */
@media (min-width: 600px) {
  .calculator-buttons {
    max-width: 400px;
    margin: 0 auto;
  }

  .calculator-display {
    max-width: 400px;
    margin-left: auto;
    margin-right: auto;
  }
}

/* 深色模式优化 */
@media (prefers-color-scheme: dark) {
  .calculator {
    background: #1c1c1e;
  }
}

/* 滚动条针对深色背景优化 */
.calculator:hover::-webkit-scrollbar-thumb {
  background-color: rgba(255, 255, 255, 0.2);
  box-shadow: 0 0 1px rgba(255, 255, 255, 0.1);
  opacity: 1;
}

.calculator::-webkit-scrollbar-thumb:hover {
  background-color: rgba(255, 255, 255, 0.3);
  box-shadow: 0 0 2px rgba(255, 255, 255, 0.15);
}

.calculator::-webkit-scrollbar-thumb:active {
  background-color: rgba(255, 255, 255, 0.4);
  box-shadow: 0 0 3px rgba(255, 255, 255, 0.2);
}
</style>

